package com.zretc.service.impl;

import com.zretc.dao.PermissionMapper;
import com.zretc.dao.RoleMapper;
import com.zretc.entity.Permission;
import com.zretc.entity.ResponseResult;
import com.zretc.entity.Role;
import com.zretc.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<Role> finAll() {
        return roleMapper.findAll();
    }

    @Override
    public List<Permission> finAllPermission() {
        return permissionMapper.findAll();
    }

    @Override
    public List<Integer> findPermissionIdByRoleId(Integer roleId) {
        return permissionMapper.findPermissionIdByRoleId(roleId);
    }

    @Override
    @Transactional
    public ResponseResult deleteRole(Integer roleId) {
        roleMapper.deleteRole(roleId);
        permissionMapper.deleteRolePermission(roleId);
        return ResponseResult.ok("删除成功");
    }

    @Override
    public ResponseResult addRole(Role role) {
        if (!role.getRoleName().startsWith("ROLE_")) {
            role.setRoleName("ROLE_" + role.getRoleName());
        }
        if(roleMapper.insertRole(role)==1){
            return ResponseResult.ok("添加成功");
        }
        return ResponseResult.error("添加失败");
    }

    @Override
    @Transactional
    public ResponseResult updateRole(Integer roleId, Integer[] permissionIds) {
        // 先删除角色权限关系表数据
        permissionMapper.deleteRolePermission(roleId);
        // 判断permissionIds是否为空
        if (permissionIds == null || permissionIds.length == 0) {
            return ResponseResult.ok("更新成功");
        }
        if(roleMapper.insertRecord(roleId, permissionIds)>0){
            return ResponseResult.ok("更新成功");
        }
        return ResponseResult.error("更新失败");
    }

    @Override
    @Transactional
    public ResponseResult updateUserRole(Integer userId, Integer[] roleIds) {
        if(roleIds == null || roleIds.length == 0){
            return ResponseResult.ok("更新成功");
        }
        // 先删除用户的所有角色
        roleMapper.delete(userId);
        // 再添加角色
        if(roleMapper.insert(userId,roleIds)>0){
            return ResponseResult.ok("更新成功");
        }
        return ResponseResult.error("更新失败");
    }
}
